package com.uhf.gun

import android.media.AudioManager
import android.media.SoundPool
import android.os.Bundle
import android.os.PersistableBundle
import android.util.Log
import android.view.KeyEvent
import com.rscja.deviceapi.RFIDWithUHFUART
import com.rscja.deviceapi.entity.UHFTAGInfo
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugins.GeneratedPluginRegistrant


class MainActivity: FlutterActivity() {

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
//        super.configureFlutterEngine(flutterEngine)
        GeneratedPluginRegistrant.registerWith(flutterEngine)

        val android = MethodChannel(flutterEngine.dartExecutor.binaryMessenger,"toAndroid")

        android.setMethodCallHandler { call, result ->
            run {
                if (call.method != null) {
                    if ("initUHF" == call.method) {
                        result.success(initUHF())
                    }
                    if ("setPower" == call.method) {
                        result.success(setPower(call.arguments as Int))
                    }

                } else {
                    result.notImplemented()
                }
            }
        }

        toFlutter = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "toFlutter")
        initSound()

    }

    override fun onDestroy() {
        super.onDestroy()
        free()
    }

    private lateinit var toFlutter: MethodChannel
    private var mReader: RFIDWithUHFUART? = null
    private var inventory = false

    private fun initUHF(): String {
        var result = ""
        try {
            mReader = RFIDWithUHFUART.getInstance()
            result = "success"
        } catch (e: Exception) {
            e.printStackTrace()
            result = "fail"
        }
        if (mReader != null) {
            mReader!!.init()
        }
        return result
    }

    private fun free() {
        try {
            if(mReader != null){
                mReader!!.free()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun setPower(power:Int): String {
        var result = ""
        try {
            if(mReader != null){
                mReader!!.power = power
            }
            result = "success"
        } catch (e: Exception) {
            e.printStackTrace()
            result = "fail"
        }
        return result
    }


    private fun startInventory(){
        if(mReader == null){
            return
        }
        if(inventory){
            return
        }
        inventory = true
        mReader!!.setInventoryCallback { uhftagInfo ->
            runOnUiThread {
                sendData(uhftagInfo.epc+uhftagInfo.rssi)
            }
            playSound(1)
        }
        mReader!!.startInventoryTag()
    }


    private fun sendData(data:String){
        toFlutter.invokeMethod("data", data, object : MethodChannel.Result {

            override fun success(o: Any?) {

            }

            override fun error(s: String, s1: String?, o: Any?) {
            }

            override fun notImplemented() {
            }

        })
    }

    private fun stopInventory(){
        if(mReader == null){
            return
        }
        inventory = false
        mReader!!.stopInventory()
    }

    override fun dispatchKeyEvent(event: KeyEvent): Boolean {
        if (event.keyCode == 293 && event.action == KeyEvent.ACTION_DOWN) {
            try {
                startInventory()
            }catch  (e:Exception){
                e.printStackTrace()
            }
            return false
        }
        if (event.keyCode == 293 && event.action == KeyEvent.ACTION_UP) {
            try {
                stopInventory()
            }catch  (e:Exception){
                e.printStackTrace()
            }
            return false
        }
        return super.dispatchKeyEvent(event)
    }

    private var am: AudioManager? = null
    var soundMap = HashMap<Int, Int>()
    private var soundPool: SoundPool? = null
    private var volumnRatio = 0f

    private fun initSound() {
        soundPool = SoundPool(10, AudioManager.STREAM_MUSIC, 5)
        soundMap[1] = soundPool!!.load(this, R.raw.barcodebeep, 1)
        soundMap[2] = soundPool!!.load(this, R.raw.serror, 1)
        am = this.getSystemService(AUDIO_SERVICE) as AudioManager
    }

    /**
     * 播放提示音
     *
     * @param id 成功1，失败2
     */
    fun playSound(id: Int) {
        val audioMaxVolume: Float =
            am!!.getStreamMaxVolume(AudioManager.STREAM_MUSIC).toFloat() // 返回当前AudioManager对象的最大音量值
        val audioCurrentVolume: Float =
            am!!.getStreamVolume(AudioManager.STREAM_MUSIC).toFloat() // 返回当前AudioManager对象的音量值
        volumnRatio = audioCurrentVolume / audioMaxVolume
        try {
            soundPool!!.play(
                soundMap[id]!!, volumnRatio,  // 左声道音量
                volumnRatio,  // 右声道音量
                1,  // 优先级，0为最低
                0,  // 循环次数，0不循环，-1永远循环
                1f // 回放速度 ，该值在0.5-2.0之间，1为正常速度
            )
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }


}
